package com.p2p.Androidp2p;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

import android.os.Environment;
import android.util.Log;

/**
 * Server class to start a server on android phone
 * @author Santiago
 *
 */
public class Serverp2p implements Runnable {

	private Socket client = null;
	private File sendFile = null;
    
	public Serverp2p(Socket c)
	{
	    client = c;
	}
	
	/**
	 * runs through the server steps (1 iteration will change so its always looping)
	 */
	public void run() 
	{	
	    TransferFile();
	    close();
	    Peer.update();
	    Log.d("ANDROIDP2P S:run", "file sending done");
	}
 
	
    /**
     * transfers file off of the server to the client
     */
	public void TransferFile()
	{
		
	    //chunksize has to be less then 8k
	    int chunkSize = 5000;
	    int done = 0;
	    byte[] fileArray = new byte[chunkSize];
	    
		//gets the file name the server will fetch with
	    getFile();
	    
	    //this checks the the file to make sure it is in your shared Directory
	    checkFileName();
        
	    //the actual transferring of the byte to the client
	    try
	    {
        	//reads the file into a size the array
        	FileInputStream fileIn = new FileInputStream(sendFile);
        	BufferedInputStream bufferIn = new BufferedInputStream(fileIn);
        	OutputStream output = client.getOutputStream();
        	
        	//sends the array to the client
        	do
        	{
        	    done = bufferIn.read(fileArray,0, fileArray.length);
        	    if( done >=0)
        	    {
        		output.write(fileArray,0, done);
        	    }
        	}while(done > -1);
        	
       	    	output.flush();
       	    	output.close();
       	    	bufferIn.close();
       	    	fileIn.close();
        	
	    } 
	    catch (FileNotFoundException e)
	    {
		Log.d("ANDROIDP2P S:transferFile", e.getMessage());
        	return;
        	
	    } catch (Exception e)
	    {
        	Log.d("ANDROIDP2P S:transferFile", e.getMessage());
        	return;
	    }
	}
	
	/**
	 * gets the name of the file to transfer
	 * @return - name of the file being transferred
	 */
	private String getFile()
	{
		String filename = null;
		try { 
		BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); 
            	filename =  in.readLine(); 

		} catch(Exception e) {
		    Log.d("ANDROIDP2P S:getFile", e.getMessage());
		    return null;
		}
          
		File temp = Environment.getExternalStorageDirectory();
		File root = new File(temp, "Shared");
          
		if(root.canRead())
		{
		    sendFile = new File(root, filename);
		}
          
		return filename;
	}
	
	/**
	 * checks to see if the file exists on the phones Shared directory
	 */
	private void checkFileName()
	{
		PrintWriter out = null;
		FileInputStream checker;
		
		try 
		{ 
			out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(client.getOutputStream())),true);	           
            
		}catch(IOException e)
		{
             		Log.d("ANDROIDP2P S:checkName", e.getMessage());
			return;
		}  
         
		try
		{
			checker = new FileInputStream(sendFile);
			checker.close();
			out.println("file is good");
		} catch (FileNotFoundException e)
		{
			out.println("error");
			Log.d("ANDROIDP2P S:checkName", e.getMessage());
			return;
		} catch(IOException e)
		{
			Log.d("ANDROIDP2P S:checkName", e.getMessage());
			return;
		}
		
	}
	
	/**
	 * closes connection between client and server
	 */
	public void close()
	{
		try {
			client.close();
		} catch (IOException e) {
			Log.d("ANDROIDP2P S:close", e.getMessage());
			System.exit(1);
		}
	}

}
